<!--
 * @name: 
 * @Author: JiaYing
 * @LastEditors: JiaYing
 * @Date: 2022-08-25 01:25:38
 * @LastEditTime: 2022-08-25 14:51:15
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 使用</title>
  </head>
  <body></body>
</html>

<script>
  (async function () {
    Promise.resolve()
      .then(() => {
        // throw new Error(1);
        return Promise.reject(1);
      })
      .catch((e) => {
        console.log("catch err=>", e);
      });

    await sleep(1000);

    await Promise.resolve()
      .then(() => {
        throw new Error(1);
        // return 1;
      })
      .then(
        (res) => {
          throw new Error(2);
        },
        (err) => {
          console.log("cb err=>", err);
        }
      )
      .catch((e) => {
        console.log("catch err=>", e);
      });

    await sleep(1000);

    function sleep(time) {
      return new Promise((reslove) => {
        setTimeout(function () {
          reslove();
        }, time);
      });
    }

    sleep(1000).then(() => {
      console.log(1);
    });

    // await sleep(1000);
    // console.log(1);

    function ajx(value) {
      const time = ((Math.random() * 10) % 5) * 200;
      console.log(time);
      return new Promise((reslove) => {
        setTimeout(() => {
          reslove(value);
        }, time);
      });
    }

    const ajxs = Array.from(Array(10)).map((v, i) => ajx(i + 1));

    Promise.all(ajxs).then((res) => {
      console.log("all", res);
    });
    Promise.race(ajxs).then((res) => {
      console.log("race", res);
    });

    const p = new Promise(function () {});
    console.log(p);

    new Promise(function (reslove, reject) {
      reject(1);
    });
    Promise.reject(2);

    console.log("===============");

    window.addEventListener("unhandledrejection", function (e) {
      console.log("unhandledrejection =>", e);
    });
  })();
</script>
